package com.spedencencies.springjdbc2.controller;

import com.spedencencies.springjdbc2.model.Event;
import com.spedencencies.springjdbc2.service.EventService;
import com.spedencencies.springjdbc2.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;


/**
 * 时间入参字符串
 * 和 java.time LocalDateTime
 * 和 mysql字段类型datetime 的映射关系转换
 *
 * @author zhizhou   2024/10/9 14:15
 */
@RestController
@RequestMapping("/api/events")
public class DateTimeController {
    private final EventService eventService;
    
    @Autowired
    public DateTimeController(EventService eventService) {
        this.eventService = eventService;
    }
    
    // 增加事件
    @PostMapping("/submit-time")
    public String submitTime(@RequestParam String dateTime) {
        LocalDateTime localDateTime =  DateUtils.parseDateTime(dateTime);
        System.out.println(localDateTime);
        LocalTime localTime =  DateUtils.parseTime(dateTime.substring(11,19));
        System.out.println(localTime);
        eventService.saveEvent(dateTime);
        return "Event time saved: " + dateTime;
    }
    
    // 根据 ID 查询事件
    @GetMapping("/{id}")
    public Event getEvent(@PathVariable Long id) {
        return eventService.getEventById(id);
    }
    
    // 更新事件
    @PutMapping("/{id}")
    public String updateEvent(@PathVariable Long id, @RequestParam String newDateTime) {
        eventService.updateEvent(id, newDateTime);
        return "Event time updated for ID: " + id;
    }
    
    // 根据 ID 删除事件
    @DeleteMapping("/{id}")
    public String deleteEvent(@PathVariable Long id) {
        eventService.deleteEvent(id);
        return "Event deleted with ID: " + id;
    }
    
    // 查询所有事件
    @GetMapping
    public List<Event> getAllEvents() {
        return eventService.getAllEvents();
    }
}
